﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Budgeter.Extensions;

namespace Budgeter.ViewModels.Budget.CreateOrEdit
{
    
    public class Saver : ISaver<ViewModel, Models.Budget>
    {
        public Models.Budget Save(Models.BudgeterContext db, ViewModel from)
        {
            bool isNew = false;
            Models.Budget to;
            if(from.ReceiptNumber == 0)
            {
                isNew = true;
                to = db.Budgets.Create();
                to.CreatedUtc = DateTime.UtcNow;
                to.ReceiptNumber = Receipt.GenerateUniqueReceiptNumber(db);
            }
            else
            {
                to = db.Budgets.FindByReceiptNumber(from.ReceiptNumber);
            }

            db.Entries.RemoveRange(to.Entries);
            foreach (var i in from.Entries.Where(x => x.Amount.GetValueOrDefault() != 0 && x.IntervalId.HasValue))
            {
                to.Entries.Add(new Models.Entry
                {
                    Amount = i.Amount.Value,
                    EntryType = db.EntryTypes.GetByCategoryAndName(i.Category, i.Name),
                    Interval = db.Intervals.First(x => x.IntervalId == i.IntervalId),
                    Budget = to,
                });
            }
            to.Interval = db.Intervals.First(x => x.IntervalId == from.IntervalId);

            if(isNew)
                to = db.Budgets.Add(to);

            db.SaveChanges();

            return to;
        }
    }

}